/**
 * 浏览器调用语音合成接口
 * @param {Object} param 百度语音合成接口参数
 * 请参考 https://ai.baidu.com/docs#/TTS-API/41ac79a6
 * @param {Object} options 跨域调用api参数
 *           timeout {number} 超时时间 默认不设置为60秒
 *           volume {number} audio控件音量，范围 0-1
 *           hidden {boolean} 是否隐藏audio控件
 *           autoDestory {boolean} 播放音频完毕后是否自动删除控件
 *           onInit {Function} 创建完audio控件后调用
 *           onSuccess {Function} 远程语音合成完成，并且返回音频文件后调用
 *           onError {Function}  远程语音合成完成，并且返回错误字符串后调用
 *           onTimeout {Function} 超时后调用，默认超时时间为60秒
 */

function btts(param, options) {
  console.log('进入百度合成链接')
  var url = 'http://tsn.baidu.com/text2audio';
  var opt = options || {};
  var p = param || {};
  // 如果浏览器支持，可以设置autoplay，但是不能兼容所有浏览器
  // var audio = document.createElement('audio');
  if (opt.autoplay) {
  }
  // 隐藏控制栏
  if (!opt.hidden) {
    //audio.setAttribute('controls', 'controls');
  } else {
    audio.style.display = 'none';
  }
  // 设置音量
  if (typeof opt.volume !== 'undefined') {
    //audio.volume = opt.volume;
  }
  // 调用onInit回调
  isFunction(opt.onInit) && opt.onInit(audio);
  // 默认超时时间60秒
  var DEFAULT_TIMEOUT = 100000;
  var timeout = opt.timeout || DEFAULT_TIMEOUT;
  // 创建XMLHttpRequest对象
  var xhr = new XMLHttpRequest();
  // 创建form参数
  var data = {};
  for (var p in param) {
    data[p] = param[p]
  }
  // 赋值预定义参数
  data.cuid = data.cuid || data.tok;
  data.ctp = 1;
  data.lan = data.lan || 'zh';
  // 序列化参数列表
  var fd = [];
  for(var k in data) {
    fd.push(k + '=' + encodeURIComponent(data[k]));
  }
  // 用来处理blob数据
  var frd = new FileReader();
  xhr.responseType = 'blob';
  // 用timeout可以更兼容的处理兼容超时
  var timer = setTimeout(function(){
    xhr.abort();
    isFunction(opt.onTimeout) && opt.onTimeout();
  }, timeout);
  // alert(xhr.readyState)
  console.log('readyState',xhr.readyState)
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      clearTimeout(timer);
      if (xhr.status == 200) {
          // 在body元素下apppend音频控件
          // document.body.append(audio);
          // document.getElementById("myaudio").removeChild(myaudio1);
          //   document.getElementById("myaudio").appendChild(audio);
          // audio.setAttribute('controls', 'controls');
          audio = document.getElementsByTagName("audio")[0];
          // console.log('url:'+URL.createObjectURL(xhr.response));
          audio.setAttribute('src', url+'?'+fd.join('&'));
          if (opt.autoDestory) {
            audio.onended = function() {
              //onSpeakCompleted();
              //document.getElementById("audio_div").removeChild(audio);//alert(cur_num);
              cur_num=cur_num+1;
              tts();
            }
          }
          isFunction(opt.onSuccess) && opt.onSuccess(audio);
        // 用来处理错误
        if (xhr.response.type === 'application/json') {
          frd.onload = function(){
            var text = frd.result;
            isFunction(opt.onError) && opt.onError(text);
          };
          frd.readAsText(xhr.response);
        }
      }
    }
  }
  xhr.open('POST', url);
  xhr.send(fd.join('&'));

  // 判断是否是函数
  function isFunction(obj) {
    if (Object.prototype.toString.call(obj) === '[object Function]') {
      return true;
    }
    return false;
  }
}
//播放按钮
function play() {
  audio = document.getElementById('myaudio').getElementsByTagName('audio')[0];
  if (audio === null) {
    //alert('请先点击合成')
    alert('请先点击语音播报');
  } else {
    audio.play();
    falg = 0;
  }
}

var falg = 0;

//暂停按钮
function pause(id,data) {

  if(id != itemid){
    audioPlay(data,id);
    document.getElementById('playAudio').setAttribute('src',require('../../static/images/play.png'));
  }else{
    num--;
    audio = document.getElementById('myaudio').getElementsByTagName('audio')[0];
    if (audio === null) {
      //alert('请先点击合成')
      alert('请先点击语音播报');
    } else {
      audio.pause();
      falg = 1;
    }
  }
}

//取消按钮
function cancel() {
  if (audio === null) {
    // alert('请先点击合成')
    alert('请先点击语音播报');
  } else {
    audio.pause();
    document.body.removeChild(audio);
    audio = null;
  }
}
// 初始化变量
var audio = document.createElement('audio');

var isPlaying = false;
// 合成按钮
let cur_num=0;
function tts() {
  console.log('进入合成');
  if(cur_num>=text_array.length){
    cur_num = 0;
    document.getElementById('playAudio').setAttribute('src',require('../../static/images/pause.png'));
    num--; // 语音播放完后。。
    falg = 0;
    return;
  }
  let text =text_array[cur_num];
  console.log('text_0',text);
  var baiduToken=localStorage.getItem('baiduToken');
  // 调用语音合成接口
  // 参数含义请参考 https://ai.baidu.com/docs#/TTS-API/41ac79a6
  //'24.31e4ac515ddc2d88d9c79b452a8927ac.2592000.1545638600.282335-14569381',
  audio = btts({
    tex: text,
    tok: baiduToken,
    spd: 5,
    pit: 5,
    vol: 15,
    per: 0,
  }, {
    volume: 0.5,
    autoDestory: true,
    timeout: 1000000,
    hidden: false,
    onInit: function (htmlAudioElement) {
    },
    onSuccess: function(htmlAudioElement) {
      audio = htmlAudioElement;
        audio.play();
      console.log('textz-array',text_array.length);
    },
    onError: function(text) {
      alert(text)
    },
    onTimeout: function () {
      alert('timeout')
    }
  });
}

// dom加载完毕回调
function ready(callback){
  var doc = document;
  if (doc.addEventListener) {
    doc.addEventListener('DOMContentLoaded', function() {
      callback();
    }, false);
  } else if (doc.attachEvent) {
    doc.attachEvent('onreadystatechange', function() {
      if (doc.readyState === 'complete') {
        callback();
      }
    });
  }
}
function htmlToText(str){
  str = str.replace(/<\/?[^>]*>/g,''); //去除HTML tag
  str = str.replace(/[|]*\n/, ''); //去除行尾空白
  //str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
  str=str.replace(/&nbsp;/ig,'');//去掉&nbsp;
  return str;
}
var text_array = new Array();

var itemid;

function audioPlay(data,id){

  if(id != itemid){
    falg = 0;
    num = 1;
  }
  itemid = id;

  num++;

  if(falg == 1){
    play();
  }else {
    console.log('text_array', text_array.length);
    if (text_array.length > 0) {
      text_array = [];
    }
    console.log('text_array', text_array.length);
    if (audio == null) {
      audio = document.createElement('audio');
    }
    // document.getElementById("myaudio1").remove();
    document.getElementById("myaudio").appendChild(audio);
    // audio.setAttribute('controls', 'controls');

    let nr = data;
    console.log('js_myspan', nr);
    // debugger
    if (!nr) return;
    var base = 200;
    nr = htmlToText(nr);
    console.log('nr', nr);

    if (nr.length > base) {
      do {
        text_array.push(nr.substring(0, base));
        nr = nr.substring(base);
        console.log('do_nr', nr);
      }
      while (nr.length > base);
      if (nr != '') {
        text_array.push(nr);
      }
    } else {
      text_array.push(nr);
    }
    for (let i = 0; i < text_array.length; i++) {
      console.log('text_array:' + text_array[i]);
    }
    tts();
  }
}

var num = 1;
function getnum() {
  return num;
}

export {
  audioPlay,
  pause,
  getnum
}
